package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Attendance;
import com.EAsystem.entity.Course;
import com.EAsystem.service.AttendanceService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class AttendanceController {

    @Autowired
    private AttendanceService attendanceService;

    /**
     * 考勤信息管理页面
     */
    @GetMapping("/attendance")
    public String attendancePage(@RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "5") int size,
                               @RequestParam(required = false) String courseName,
                               Model model) {
        
        PageInfo<Attendance> pageInfo;
        
        // 根据条件查询
        if (courseName != null && !courseName.trim().isEmpty()) {
            Attendance searchAttendance = new Attendance();
            Course course = new Course();
            course.setName(courseName.trim());
            searchAttendance.setCourse(course);
            pageInfo = attendanceService.getAttendancesByConditionWithPage(searchAttendance, page, size);
        } else {
            pageInfo = attendanceService.getAllAttendancesWithPage(page, size);
        }
        

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        model.addAttribute("attendances", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseName", courseName);
        model.addAttribute("pageNumbers", pageNumbers);
        
        return "admin/attendance";
    }

    /**
     * 查看考勤详情
     */
    @GetMapping("/attendance/view/{id}")
    @ResponseBody
    public Map<String, Object> viewAttendance(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Attendance attendance = attendanceService.getAttendanceById(id);
            if (attendance != null) {
                result.put("success", true);
                result.put("attendance", attendance);
            } else {
                result.put("success", false);
                result.put("message", "考勤记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取考勤信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑考勤状态
     */
    @PostMapping("/attendance/edit/{id}")
    @ResponseBody
    public Map<String, Object> editAttendance(@PathVariable Long id, 
                                            @RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (status < 0 || status > 4) {
                result.put("success", false);
                result.put("message", "考勤状态无效");
                return result;
            }
            
            Attendance attendance = attendanceService.getAttendanceById(id);
            if (attendance == null) {
                result.put("success", false);
                result.put("message", "考勤记录不存在");
                return result;
            }
            
            attendance.setStatus(status);
            boolean success = attendanceService.updateAttendance(attendance);
            if (success) {
                result.put("success", true);
                result.put("message", "考勤状态更新成功");
            } else {
                result.put("success", false);
                result.put("message", "考勤状态更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除考勤记录
     */
    @GetMapping("/attendance/delete/{id}")
    public String deleteAttendance(@PathVariable Long id) {
        attendanceService.deleteAttendance(id);
        return "redirect:/admin/attendance";
    }

    /**
     * 批量删除考勤记录
     */
    @GetMapping("/attendance/batchDelete")
    public String batchDeleteAttendances(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    attendanceService.deleteAttendance(Long.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/attendance";
    }

    /**
     * 获取考勤状态列表（供前端使用）
     */
    @GetMapping("/attendance/statusList")
    @ResponseBody
    public Map<String, Object> getStatusList() {
        Map<String, Object> result = new HashMap<>();
        Map<Integer, String> statusMap = new HashMap<>();
        statusMap.put(0, "缺勤");
        statusMap.put(1, "正常");
        statusMap.put(2, "请假");
        statusMap.put(3, "迟到");
        statusMap.put(4, "早退");
        
        result.put("success", true);
        result.put("statusList", statusMap);
        return result;
    }
} 